package core.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

/**
 * 数据库连接的h2实现
 * @author lost
 *
 */
public class H2DBManager implements DBManager{
	public static Logger logger = Logger.getRootLogger() ;
	public static String rootPath = null ;
	static{
		try {
			Class.forName("org.h2.Driver");
			/**
			 * 这里由于是内嵌数据库，所以用的就是工程路径
			 */
			rootPath = ServletActionContext.getServletContext().getRealPath("/") ;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private Connection cn ;
	@Override
	public void open() throws Exception {
			logger.debug("open url:"+rootPath+"dbFiles/" + "sino") ;
			cn = DriverManager.
			            getConnection("jdbc:h2:" + rootPath+"/dbFiles/" + "sino", "admin", "");
	}

	@Override
	public void close() throws Exception {
			cn.close() ;
	}

	@Override
	public ResultSet excuteQuery(String sql) throws Exception {
			logger.info("excute sql"+sql) ;
			Statement st = cn.createStatement() ;
			return st.executeQuery(sql) ;
	}

	@Override
	public void excuteUpdate(String sql) throws Exception {
			logger.info("update sql"+sql) ;
			Statement st = cn.createStatement() ;
			st.execute(sql) ;
	}
}